package com.yiyihealth.cherriesadmin.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.yiyihealth.cherriesadmin.core.http.HttpResult;
import com.yiyihealth.cherriesadmin.core.web.BaseController;
import com.yiyihealth.cherriesadmin.model.OptionItem;
import com.yiyihealth.cherriesadmin.model.OrdScheduling;
import com.yiyihealth.cherriesadmin.model.PubHospital;
import com.yiyihealth.cherriesadmin.model.wrapper.OrdSchedulingWrapper;
import com.yiyihealth.cherriesadmin.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 日常排版(OrdScheduling)表控制层
 *
 * @author chen
 * @since 2020-09-14 20:03:45
 */
@Api(tags = "排班临时调整类")
@RestController
@RequestMapping("ordScheduling")
public class OrdSchedulingController extends BaseController<OrdScheduling, OrdSchedulingWrapper, Long> {
    /**
     * 服务对象
     */
    @Resource
    private OrdSchedulingService ordSchedulingService;
    @Resource
    private PubDepartmentsService departmentsService;
    @Resource
    private PubDoctorService doctorService;
    @Resource
    private OrdSchedulingService schedulingService;
    @Resource
    private OrdSourceDetailService ordSourceDetailService;
    @Resource
    private PubHospitalService hospitalService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate<Object, Object> redisCacheTemplate;

    @Override
    @InitBinder()
    public void initBinder(WebDataBinder binder) {
        super.setBaseService(ordSchedulingService);
    }

    @ResponseBody
    @Override

    public HttpResult updateByPrimaryKeySelective(@RequestBody OrdScheduling record) {
        schedulingService.updateByPrimaryKeySelective(record);
        redisCacheTemplate.delete("options::0");
        redisCacheTemplate.delete("options::57170");
        redisCacheTemplate.delete("options::57171");
        redisCacheTemplate.delete("options::57172");
        schedulingService.selectListForOptions(0L);
        schedulingService.selectListForOptions(57170L);
        schedulingService.selectListForOptions(57171L);
        schedulingService.selectListForOptions(57172L);
        return HttpResult.success();
    }

    /**
     * 医生停诊
     *
     * @param id
     * @param reason
     * @return
     */
    @ApiOperation(value = "医生停诊")
    @PostMapping("/doctorStopWork")
    @ResponseBody
    public HttpResult doctorStopWork(@RequestParam Long id, @RequestParam String reason) throws Exception {
        String result = ordSchedulingService.doctorStopWork(id, reason);
        try {
            ScheduledCache();
        } catch (Exception e) {
            return HttpResult.failure(e.getMessage());
        }
        return HttpResult.success(result);
    }

    /**
     * 医生批量停诊
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "医生批量停诊")
    @PostMapping("/doctorStopWorkCache")
    @ResponseBody
    public HttpResult doctorStopWorkCache() {
        redisCacheTemplate.delete("options::0");
        redisCacheTemplate.delete("options::57170");
        redisCacheTemplate.delete("options::57171");
        redisCacheTemplate.delete("options::57172");
        schedulingService.selectListForOptions(0L);
        schedulingService.selectListForOptions(57170L);
        schedulingService.selectListForOptions(57171L);
        schedulingService.selectListForOptions(57172L);
        try {
            ScheduledCache();
        } catch (Exception e) {
            return HttpResult.failure(e.getMessage());
        }
        return HttpResult.success();
    }

    @ApiOperation(value = "获取医生排班信息")
    @PostMapping("/selectListForOptions")
    @ResponseBody
    public List<OptionItem<PubHospital>> selectListForOptions(@RequestParam Long hospitalId) throws Exception {
        return schedulingService.selectListForOptions(hospitalId);
    }


    @ApiOperation(value = "号源池补录")
    @PostMapping("/schedulingCache")
    @ResponseBody
    public HttpResult schedulingCache() {
        try {
            ScheduledCache();
        } catch (Exception e) {
            return HttpResult.failure(e.getMessage());
        }
        return HttpResult.success();
    }

    private void ScheduledCache() throws Exception {
        Map<String, Object> schedulingMap = new HashMap<String, Object>(8);
        schedulingMap.put("status", "0");
        List<OrdScheduling> schedulingList = ordSchedulingService.selectList(schedulingMap);
        schedulingList = schedulingList.stream().filter(ordScheduling -> ordScheduling.getSchedulingTime().isAfter(LocalDate.now().minusDays(1))).collect(Collectors.toList());
        Duration duration = Duration.between(LocalDateTime.now(), LocalDate.now().atTime(23, 59, 59));
        if (!CollectionUtil.isEmpty(schedulingList)) {
            for (OrdScheduling scheduling : schedulingList) {
                try {
                    ordSchedulingService.schedulingCache(scheduling);
                } catch (Exception e) {
                    throw new Exception(e.getMessage());
                }
            }
        }
        redisCacheTemplate.expire("schedulingCache", duration);
    }


    @ApiOperation(value = "H5页面医生号源查询")
    @GetMapping("/selectListByHospitalIdDoctorId")
    @ResponseBody
    public HttpResult selectListByHospitalIdDoctorId(@RequestParam Long hospitalId, @RequestParam Long doctorId, @RequestParam String status, @RequestParam Long patId) throws Exception {
        return HttpResult.success(ordSchedulingService.selectListByHospitalIdDoctorId(hospitalId, doctorId, status, patId));
    }

    @ApiOperation(value = "健康通--医院排班上传")
    @PostMapping("/jktSchedulingUpload")
    @ResponseBody
    public HttpResult jktSchedulingUpload(@RequestParam Long hospitalId) throws Exception {
        try {
            ordSchedulingService.jktSchedulingUpload(hospitalId);
        }catch (Exception e){
            return HttpResult.failure(e.getMessage());
        }
        return HttpResult.success("健康通医院排班上传成功！");
    }

    @ApiOperation(value = "健康通--医院排班上传")
    @PostMapping("/jktSchedulingUploadSingle")
    @ResponseBody
    public HttpResult jktSchedulingUploadSingle(@RequestParam Long id) throws Exception {
        try {
            ordSchedulingService.jktSchedulingUploadSingle(id);
        }catch (Exception e){
            return HttpResult.failure(e.getMessage());
        }
        return HttpResult.success("健康通医院排班上传成功！");
    }


}
